//
//  TTCompanyInfoViewController.m
//  TaoTuo
//
//  Created by admin on 2019/12/20.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTCompanyInfoViewController.h"
#import "TTDianpuTextCellModel.h"
#import "TTDianpuChooseCellModel.h"
#import "TTDianpuCommonViewCell.h"
#import "TTCompanyInfoModel.h"

#import "AddressView.h"
#import "SPModalView.h"

static NSString *cellID = @"cellID";

@interface TTCompanyInfoViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableDictionary *paramsDic;
@property (nonatomic, strong) TTCompanyInfoModel *model;

@property (nonatomic, strong) AddressView *addressView;
@property (nonatomic, strong) SPModalView *modalView;

@end

@implementation TTCompanyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"企业信息";
    
    [self getCompanyInfo];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuCellModel *cellModel = self.dataArray[indexPath.row];
    
    TTDianpuCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setModel:cellModel canEdit:self.model.CompanyName.length == 0];
    return cell;
    
}

- (void)confirmUploadDatas
{
    for (TTDianpuCellModel *model in self.dataArray) {
        if (![model.title containsString:@"选填"] && model.content.length == 0) {
            [self.view makeToast:model.placeholder];
            [self.paramsDic removeAllObjects];
            return;
        }
        if ([model isKindOfClass:[TTDianpuChooseCellModel class]]) {
            if ([model.field containsString:@"_"]) {
                NSArray *fields = [model.field componentsSeparatedByString:@"_"];
                NSArray *contents = [model.content componentsSeparatedByString:@" "];
                
                [self.paramsDic setObject:contents.firstObject forKey:fields.firstObject];
                [self.paramsDic setObject:contents[1] forKey:fields[1]];
                if (contents.count > 2) {
                    [self.paramsDic setObject:contents.lastObject forKey:fields.lastObject];
                }
            } else {
                [self.paramsDic setObject:model.content forKey:model.field];
            }
        } else {
            [self.paramsDic setObject:model.content forKey:model.field];
        }
    }
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:setCompanyInfo_api parameters:self.paramsDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [[UIApplication sharedApplication].keyWindow makeToast:@"企业信息保存成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
    
    
}

- (void)getCompanyInfo
{
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:getCompanyInfo_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        self.model = [TTCompanyInfoModel modelWithJSON:responseObject];
        
        [self setupDatas];
        
        [self setupHeaderView];
        [self setupBottomView];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
    
}

- (void)chooseCityAction:(TTDianpuChooseCellModel *)model
{
    [self.modalView show];
    // 最后一列的行被点击的回调
    @weakify(self)
    self.addressView.lastComponentClickedBlock = ^(SPProvince *selectedProvince, SPCity *selectedCity, SPDistrict *selectedDistrict) {
        @strongify(self)
        [self.modalView hide];
        
        NSString *areaString = [NSString stringWithFormat:@"%@ %@",selectedProvince.fullname, selectedCity.fullname];
        
        if (selectedDistrict.fullname.length > 0) {
            areaString = [NSString stringWithFormat:@"%@ %@", areaString, selectedDistrict.fullname];
        }
        model.content = areaString;
        [self.tableView reloadRow:[self.dataArray indexOfObject:model] inSection:0 withRowAnimation:UITableViewRowAnimationFade];
    };
}

- (void)setupDatas
{
    [self.dataArray removeAllObjects];
    
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"企业名称" placeholder:@"请输入企业名称" content:self.model.CompanyName field:@"param.companyName"]];
    NSString *areaStr = nil;
    if (self.model.Province.length > 0) {
        areaStr = [NSString stringWithFormat:@"%@ %@ %@", self.model.Province, self.model.City, self.model.Area ? : @""];
    }
    [self.dataArray addObject:[TTDianpuChooseCellModel setModelWithTitle:@"企业注册地" placeholder:@"省/市/区" content:areaStr rightImageName:nil target:self selector:@selector(chooseCityAction:) field:@"param.province_param.city_param.area"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"街道" placeholder:@"街道地址" content:self.model.Address field:@"param.address"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"企业电话" placeholder:@"座机号/手机号" content:self.model.Phone field:@"param.phone"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"门店数量" placeholder:@"请输入门店数量" content:self.model.StoreNumber field:@"param.storeNumber"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"员工数量" placeholder:@"请填写真实员工数量" content:self.model.StaffNumber field:@"param.staffNumber"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"主营业务(选填)" placeholder:@"砖石、黄金、玉器" content:self.model.MainBusiness field:@"param.mainBusiness"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"加盟珠宝品牌(选填)" placeholder:@"请输入品牌名称" content:self.model.JoinJewelryBrand field:@"param.joinJewelryBrand"]];
    [self.dataArray addObject:[TTDianpuTextCellModel setModelWithTitle:@"主要供应商(选填)" placeholder:@"请输入供货商名称" content:self.model.MainSupplier field:@"param.mainSupplier"]];
    
    [self.tableView reloadData];
    
}

- (void)setupHeaderView
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 100)];
    headerView.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [UILabel labelWithTitle:@"企业信息" color:UIColorHex(333333) fontSize:24];
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(30);
        make.left.mas_equalTo(15);
    }];
    
    NSString *content = @"完善企业信息，有利于企业专属商城的信息展示(完善后不可修改)";
    UILabel *contentLabel = [UILabel labelWithTitle:content color:UIColorHex(666666) fontSize:15];
    contentLabel.numberOfLines = 0;
    [headerView addSubview:contentLabel];
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel);
        make.right.equalTo(headerView).mas_offset(-15);
        make.top.equalTo(titleLabel.mas_bottom).mas_offset(10);
    }];
    
    [headerView layoutIfNeeded];
    
    headerView.height = contentLabel.bottom + 10;
    self.tableView.tableHeaderView = headerView;
    
}

- (void)setupBottomView
{
    if (self.model.CompanyName.length > 0) {
        [_tableView mas_remakeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
        return;
    }
    UIButton *confirmBtn = [UIButton createButtonWithTitle:@"提交" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(confirmUploadDatas)];
    confirmBtn.layer.cornerRadius = 22.5;
    [self.view addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-10);
        make.left.mas_equalTo(50);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(45);
    }];
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 80;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTDianpuCommonViewCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-65);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (SPModalView *)modalView
{
    if (!_modalView) {
        _modalView = [[SPModalView alloc] initWithView:self.addressView inBaseViewController:self];
        _modalView.narrowedOff = YES;
    }
    return _modalView;
}

- (AddressView *)addressView {
    
    if (!_addressView) {
        _addressView = [[AddressView alloc] init];
        _addressView.frame = CGRectMake(0, 0, kScreenWidth, 400);
        _addressView.topLabel.text = @"请选择企业注册地";
        NSString *path = [[NSBundle mainBundle] pathForResource:@"area.plist" ofType:nil];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        _addressView.datas = arr;
    }
    return _addressView;
}

- (NSMutableDictionary *)paramsDic
{
    if (!_paramsDic) {
        _paramsDic = [NSMutableDictionary dictionary];
    }
    return _paramsDic;
}

@end
